package com.sjsu.aws.simplocks;

/**
 * 
 * @author Shweta Dattatreya
 * 
 */
public class SimpleLockTestNode extends Thread {

	String name;
	SimpleLock lock;
	boolean lockRequested;
	boolean lockAcquired;

	private class LockListenerImpl implements LockListener {
		public void lockAcquired() {
			lockAcquired = true;
			System.out.println(name + " : Acquired Lock");
			System.out.println(name + " is the Leader");
		}

		public void lockReleased() {
			System.out.println(name + " : Released Lock");
		}
	}

	/**
	 * 
	 * @param n
	 */
	public SimpleLockTestNode(String n) {
		name = n;
		lockAcquired = false;
		/*
		 * try { lock = new SimpleLock(); lock.setLockListener(new
		 * LockListenerImpl()); } catch (Exception e) { e.printStackTrace(); }
		 */
	}

	/**
	 * 
	 * @return
	 */
	int getWaitTime() {
		double rand = Math.random();
		int wait = (int) (rand * 100);
		return (wait * 5);
	}

	public void run() {
		try {
			// request lock
			if (!lockRequested) {
				Thread.sleep(getWaitTime() * 10);
				lock = new SimpleLock();
				lock.setLockListener(new LockListenerImpl());
				lock.lock();
			}
			// wait till lock is acquired
			while (!lockAcquired) {
				Thread.sleep(getWaitTime() * 10);
			}
			// release lock
			Thread.sleep(getWaitTime() * 10);
			// To test ephemeral node comment next two lines
			lock.unlock();
			System.out.println(name + " : Exiting...");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}